package com.example.robertluozizhao.framecollectdemo.view.custom;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Typeface;
import android.os.Build;
import androidx.annotation.Nullable;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.example.robertluozizhao.framecollectdemo.R;
import com.example.robertluozizhao.framecollectdemo.data.test.TransactionBean;
import com.example.robertluozizhao.framecollectdemo.util.DateUtil;

import java.io.UnsupportedEncodingException;
import java.util.List;


/**
 * @author luo_zi_zhao
 * @version V1.0 当前版本描述信息
 * @FileName com.example.robertluozizhao.framecollectdemo.view.custom
 * @date 2019/4/12 17:01
 */

public class TransactionProgressView extends View {

    /**
     * 点与点的基本间隔
     */
    private float baseInterval = 200;
    /**
     * 进度条基础长度（当数据list.size > 0 ）
     */
    private float initLength = 60;

    /**
     * 进度条颜色
     */
    private int progressColor;

    /**
     * 进度条宽度
     */
    private float progressWidth;
    /**
     * 正常事务 圆半径
     */
    private float normalCircleRadius;

    /**
     * 正常事务 圆颜色
     */
    private int normalCircleColor;
    /**
     * 当前事务 圆半径
     */
    private float currentCircleRadius;
    /**
     * 当前事务 圆颜色
     */
    private int currentCircleColor;

    /**
     * 屏幕宽高像素
     */
    private float mWidthPx;

    private int mHeightPx;
    /**
     * 数据源
     */
    private List<TransactionBean> mDataSource;

    /**
     * 文字绘制的X轴坐标
     * 坐标系整个view 左上角
     */
    private float mContentX = 100;

    /**
     * 事务进度条绘制X轴坐标
     */
    private float mProgressCenterX = 60;
    /**
     * 事务进度条绘制Y轴坐标
     */
    private float mProgressCenterY = 100;

    /**
     * 文字大小
     */
    private float contentTextSize = 18;

    private Paint mPaint;


    public TransactionProgressView(Context context) {
        this(context, null);
    }

    @SuppressLint("ResourceAsColor")
    public TransactionProgressView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.transactionProgress);
        baseInterval = typedArray.getDimension(R.styleable.transactionProgress_baseInterval, baseInterval);
        initLength = typedArray.getDimension(R.styleable.transactionProgress_initLength, initLength);
        progressWidth = typedArray.getDimension(R.styleable.transactionProgress_progressWidth, progressWidth);
        progressColor = typedArray.getColor(R.styleable.transactionProgress_progressColor, R.color.blue);

        normalCircleRadius = typedArray.getDimension(R.styleable.transactionProgress_normalCircleRadius, progressWidth / 2 + 20);
        currentCircleRadius = typedArray.getDimension(R.styleable.transactionProgress_currentCircleRadius, progressWidth / 2 + 50);
        normalCircleColor = typedArray.getColor(R.styleable.transactionProgress_normalCircleColor, R.color.gray);
        currentCircleColor = typedArray.getColor(R.styleable.transactionProgress_currentCircleColor, R.color.gray);
        contentTextSize = typedArray.getDimension(R.styleable.transactionProgress_contentTextSize, contentTextSize);
        typedArray.recycle();

        mWidthPx = getContext().getResources().getDisplayMetrics().widthPixels;
        mHeightPx = getContext().getResources().getDisplayMetrics().heightPixels;

        /**
         * 关闭硬件加速
         */
        setLayerType(View.LAYER_TYPE_HARDWARE, null);
//        setLayerType(View.LAYER_TYPE_SOFTWARE,null);

    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        float x = getX();
        float translationX = getTranslationX();
        int[] locationInWin = new int[2];
        int[] locationOnScreen = new int[2];
        getLocationInWindow(locationInWin);
        getLocationOnScreen(locationOnScreen);

        Log.e("onMeasure", "widthMode:" + widthMode + ",heightMode:" + heightMode);
        Log.e("onMeasure", "widthSize:" + widthSize + ",heightSize:" + heightSize);
        Log.e("onMeasure", "测量前 getX:" + x + ",getTranslationX:" + translationX);
        Log.e("onMeasure", "测量前 locationInWin Y:" + locationInWin[1] + ",locationOnScreen Y:" + locationOnScreen[1]);

//        if (widthMode== MeasureSpec.AT_MOST&&heightMode== MeasureSpec.AT_MOST) {
        setMeasuredDimension((int) mWidthPx, mHeightPx);
/*        }else if (widthMode== MeasureSpec.AT_MOST){
            setMeasuredDimension((int) mWidthPx,heightSize);
        }else if (heightMode== MeasureSpec.AT_MOST){
            setMeasuredDimension((int) widthSize,mHeightPx);
        }*/

        x = getX();
        translationX = getTranslationX();
        getLocationInWindow(locationInWin);
        getLocationOnScreen(locationOnScreen);

        Log.e("onMeasure", "测量后 getX:" + x + ",getTranslationX:" + translationX);
        Log.e("onMeasure", "测量后 locationInWin Y:" + locationInWin[1] + ",locationOnScreen Y:" + locationOnScreen[1]);

    }

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onDraw(Canvas canvas) {
        mPaint = new Paint();
        //painit 样式
        mPaint.setColor(progressColor);
        mPaint.setStrokeWidth(progressWidth);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setAntiAlias(true);//抗锯齿super.onDraw(canvas);

        //绘制进度条
        drawTransation(canvas);

    }

    private void drawTransation(Canvas canvas) {

        /**
         * 文字统计 高度
         */
        int textHeightTotal = 0;

        /**
         * 圆心之间的距离
         */
        float circlePointDistance = 0;

        /**
         * 圆心y 坐标
         */
        float circlePointY = 0;

        /**
         * 是否执行到当前任务
         */
        boolean isCurrentTransaction;


        if (mDataSource == null || mDataSource.size() <= 0) {
            String emptyTip = "无数据";
            TextPaint textPaint = new TextPaint();
            textPaint.setColor(progressColor);
            float textWidth = textPaint.measureText(emptyTip);
            canvas.drawText(emptyTip, mWidthPx - (textWidth / 2), mHeightPx / 2, textPaint);
            return;
        }

        int dataSize = mDataSource.size();
        int differenceFormTimeNum = getDifferenceFormTimeNum(mDataSource);


        for (int i = 0; i < dataSize; i++) {
            TransactionBean itemBean = mDataSource.get(i);
            String startTimeStr = itemBean.getStartTime();
            String endTimeStr = itemBean.getEndTime();
            long startTime = DateUtil.stringToLong(startTimeStr, DateUtil.FORMAT_YYYY_MM_DD_HH_MM);
            long endTime = DateUtil.stringToLong(endTimeStr, DateUtil.FORMAT_YYYY_MM_DD_HH_MM);
            long currentTimeMillis = System.currentTimeMillis();

            //计算两个事务的时间差
            int transActionHourDiffNum = 0;
            if ((i < dataSize - 1)) {
                transActionHourDiffNum = getIntervalNumByTime(startTimeStr, mDataSource.get(i + 1).getStartTime(), DateUtil.FORMAT_YYYY_MM_DD_HH_MM);
            }

            //画圆
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setStyle(Paint.Style.FILL);
            float circleRadius = normalCircleRadius;
            if (startTime <= currentTimeMillis && endTime >= currentTimeMillis) {
                paint.setColor(currentCircleColor);
                circleRadius = currentCircleRadius;
                isCurrentTransaction = true;
            } else {
                paint.setColor(normalCircleColor);
                isCurrentTransaction = false;
            }
            circlePointY = initLength + mProgressCenterY + circlePointDistance;
            canvas.drawCircle(mProgressCenterX, circlePointY, circleRadius, paint);

            //绘制文字,返回文字高度
            int textLinsHeight = drawTransationText(canvas, itemBean.getStartTime() + " - " + itemBean.getEndTime() + "    " + itemBean.getContent()
                    , circlePointY, isCurrentTransaction);

            //圆心之间的距离
            circlePointDistance += baseInterval + (normalCircleRadius / 2 + currentCircleRadius / 2) + (transActionHourDiffNum * baseInterval) + textLinsHeight;
            textHeightTotal += textLinsHeight;
        }


        //画进度条Progress
        mPaint.setStrokeCap(Paint.Cap.SQUARE);
        Path path = new Path();
        path.moveTo(mProgressCenterX, mProgressCenterY);
//        path.lineTo(mProgressCenterX, mProgressCenterY + baseInterval * dataSize + 2 * initLength + differenceFormTimeNum * baseInterval + textHeightTotal);
        path.lineTo(mProgressCenterX, circlePointY + baseInterval);
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));
        canvas.drawPath(path, mPaint);

        if (circlePointY + baseInterval > mHeightPx) {
            mHeightPx = (int) (circlePointY + baseInterval);
            invalidate();
        }


    }

    private int getIntervalNumByTime(String timeOne, String timeTwo, String timeType) {
        long startOneTime = DateUtil.stringToLong(timeOne, timeType);
        long startTwoTime = DateUtil.stringToLong(timeTwo, timeType);
        return (int) ((startTwoTime - startOneTime) / (1000 * 60 * 60));
    }

    private int getDifferenceFormTimeNum(List<TransactionBean> mDataSource) {
        if (mDataSource != null && mDataSource.size() > 1) {
            int intervalNum = 0;
            for (int i = 0; i < mDataSource.size() - 1; i++) {
                TransactionBean oneBean = mDataSource.get(i);
                TransactionBean twoBean = mDataSource.get(i + 1);
                /**
                 * 计为1 表示就算时间相差在一小时内 也算一个间距
                 */
                int numByTime = getIntervalNumByTime(oneBean.getStartTime(), twoBean.getStartTime(), DateUtil.FORMAT_YYYY_MM_DD_HH_MM);
                if (numByTime <= 0) {
                    numByTime = 1;
                }
                intervalNum += numByTime;
            }
            return intervalNum;
        }
        return 0;
    }


    @SuppressLint("ResourceAsColor")
    private int drawTransationText(Canvas canvas, String content, float circlePointY, boolean isCurrentTransaction) {
        canvas.save();
        TextPaint textPaint = new TextPaint();
        textPaint.setTextSize(contentTextSize);
        textPaint.setTypeface(Typeface.DEFAULT_BOLD);
        textPaint.setAntiAlias(true);
        if (isCurrentTransaction) {
            textPaint.setColor(currentCircleColor);
        } else {
            textPaint.setColor(normalCircleColor);
        }
        /**
         * 计算文字高度
         */
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        float textHeight = fontMetrics.bottom - fontMetrics.top;

        String textTest = null;
        try {
            textTest = new String(content.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        canvas.translate(mContentX, circlePointY - (textHeight / 2));
        StaticLayout staticLayout = new StaticLayout(textTest, textPaint, (int) (mWidthPx - mContentX), Layout.Alignment.ALIGN_NORMAL,
                1, 0, true);
        staticLayout.draw(canvas);
        canvas.restore();

        //计算多行文字高度，并返回
        int lins = (int) ((textPaint.measureText(textTest) - 2 * mContentX) / (mWidthPx - 2 * mContentX));
        return (int) (textHeight * lins);
    }


    /**
     * @desc 绘制文字
     * @author luo_zi_zhao
     * @date create at 2019/4/15 10:27
     */
    @SuppressLint("ResourceAsColor")
    private void drawText(Canvas canvas, Paint paint) {
        //1.单行 普通绘制文字
        String text = "你好呀！！！ABce 2385";
//        String text1 = "00000000000000000000,/..,.0000001111111111111111111,/,/1111111122222222222,/./.222222222aaaaaaaaSFSDFSDFSSF,/.,/,.";
        String text1 = "螺sfs0蛳粉j龙sfdfssf卷风楼上的房间415616了开始就发sfssfsfsfsf上来slfslfjsf感受感受爽肤水sf11s3131";
        paint.setColor(R.color.transaction_normal_blue);
        paint.setTypeface(Typeface.DEFAULT);
        paint.setTextSize(30);
        float textWidth = paint.measureText(text);

        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        float ascent = Math.abs(fontMetrics.ascent);
        canvas.drawText(text, 200, initLength + mProgressCenterX + (ascent / 2), paint);


        //2.多行 staticLayout 绘制文字
        canvas.save();
        TextPaint textPaint = new TextPaint();
        textPaint.setTextSize(30);
        textPaint.setTypeface(Typeface.DEFAULT_BOLD);
        textPaint.setColor(R.color.transaction_current_green);
        textPaint.setAntiAlias(true);
        /**
         * 计算文字高度
         */
        Paint.FontMetrics fontMetrics1 = textPaint.getFontMetrics();
        float textHeight = fontMetrics1.bottom - fontMetrics1.top;

        String textTest = null;
        try {
            textTest = new String(text1.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        canvas.translate(mContentX, initLength + mProgressCenterY + baseInterval + (normalCircleRadius / 2 + currentCircleRadius / 2) - (textHeight / 2));
        StaticLayout staticLayout = new StaticLayout(textTest, textPaint, (int) (mWidthPx - mContentX), Layout.Alignment.ALIGN_NORMAL,
                1, 20, true);
//        canvas.drawText(text1,200,initLength+100+baseInterval+(normalCircleRadius/2+currentCircleRadius/2)+(ascent/2),paint);
        staticLayout.draw(canvas);
        canvas.restore();
    }

    /**
     * 绘制扇形
     *
     * @param canvas
     * @param paint
     */
    private void drawArch(Canvas canvas, Paint paint) {
        /**
         * startAngle 开始绘制的角度（x轴正方向为0 ）
         * sweepAngle 划过的度数 （正数 顺时针方向；负数 逆时针方向 ）
         * useCenter (是否已中心点闭环  true闭环成扇形 false不闭环成弧形)
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            canvas.drawArc(400, 200, 800, 600, 20, 100, false, paint);
            canvas.drawArc(400, 200, 800, 600, -20, -100, false, paint);
            paint.setStyle(Paint.Style.STROKE);
            canvas.drawArc(400, 200, 800, 600, 160, 40, true, paint);
        }
    }

    /**
     * 绘制点
     *
     * @param canvas
     */
    private void drawPoint(Canvas canvas) {
        Paint paint = new Paint();
        paint.setStrokeWidth(50);
        paint.setColor(Color.argb(255, 255, 0, 0));
        float[] pointXY = {500, 100, 500, 520, 500, 1000};
        /**
         * offset 跳过的数据
         * count 起作用的数据个数
         */
        canvas.drawPoints(pointXY, 0, 6, paint);
    }


    public List<TransactionBean> getmDataSource() {
        return mDataSource;
    }

    public void setmDataSource(List<TransactionBean> mDataSource) {
        this.mDataSource = mDataSource;
        invalidate();
    }

    public void addDataItem(TransactionBean bean) {
        if (mDataSource != null) {
            mDataSource.add(bean);
            invalidate();
        }
    }
}
